const fs = require("fs");
const path = require("path");

function readJSON(filePath) {
  let packageJson = fs.readFileSync(filePath);
  let json = JSON.parse(packageJson.toString());
  return recombination(json);
}

function recombination(json) {
  try {
    let packageMsg = fs.readFileSync(`${json.project}/mps-deploy-version.json`);
    let version = JSON.parse(packageMsg.toString());
    let prod = [];
    json.deploy.forEach((item) => {
      prod.push({
        project: json.project,
        type: json.type,
        desc: version.desc,
        version: version.version,
        es6: json.es6,
        name: item.name,
        appid: item.appid,
        key: item.key,
      });
    });
    return prod;
  } catch (err) {
    console.log(`Error: ${err}`)
  }

}

class Log {
  static writeLog(time, txt) {
    let isHas = this.isHasFile("C:", "mps-deploy-log");
    if (!isHas) {
      fs.mkdir(`C:/mps-deploy-log`, (err) => {
        if (err) {
          console.error("┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
          console.error("Mps cannot create log file on C disk");
          console.error("Please open disk file read-write permission and run as administrator");
          console.error("Error: " + err);
          console.error("┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
          return;
        }
      });
    } else {
      this.write(time, txt);
    }
  }
  static isHasFile(path, file) {
    let fileDir = fs.readdirSync(path);
    let fileArray = [];
    fileDir.forEach((item) => {
      fileArray.push(item);
    });
    return fileArray.indexOf(file) === -1 ? false : true;
  }
  static write(time, txt) {
    let isHas = this.isHasFile("C:/mps-deploy-log", `mps-deploy${time}.log`);
    if (isHas) {
      fs.appendFileSync(`C:/mps-deploy-log/mps-deploy${time}.log`, txt);
    } else {
      fs.writeFileSync(`C:/mps-deploy-log/mps-deploy${time}.log`, txt);
    }
  }
}

function getPackageSize(address) {
  let packageMsg = fs.readFileSync(`${address}/app.json`);
  let app = JSON.parse(packageMsg.toString());
  let countSize = getDirSize(address)
  let subPackages = {};
  let indexPage = app.pages[0];
  if (app.hasOwnProperty("subPackages")) {
    app.subPackages.forEach((item) => {
      subPackages[item.root] = getDirSize(`${address}/${item.root}`)
    });
  }
  return { countSize, subPackages, indexPage };
}

function getDirSize(dir, size = 0) {
  let stats = fs.statSync(dir);
  if (stats.isFile()) {
    size += stats.size
    return size; 
  }
  let readRes = fs.readdirSync(dir);
  if (readRes.length === 0) {
    return size;
  }
  for (let i = 0; i < readRes.length; i++) {
    size = getDirSize(path.join(dir, readRes[i]), size)
    if (i === readRes.length - 1) {
      return size;
    }
  }
}

function checkPackageSize(count = 0, subPackages = {}) {
  for (let key in subPackages) {
    if (subPackages[key] >= 2097152) {
      return {isPass: false, msg: 'The size of a single package cannot exceed 2MB'}
    }
  }
  if (count >=  (Object.keys(subPackages).length + 1) * 1048576) {
    return {isPass: false, msg: `Package source exceed max limit ${Object.keys(subPackages).length + 1}MB`}
  }
  if (count >=  16 * 1048576) {
    return {isPass: false, msg: `Package source exceed max limit 16MB`}
  }
  return {isPass: true}
}

module.exports = { readJSON, Log, recombination, getPackageSize, checkPackageSize };
